package com.oppo.MarkBook.dialog;

import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.MessageDialogBuilder;
import com.intellij.ui.EditorTextField;
import com.oppo.MarkBook.data.DataCenter;
import com.oppo.MarkBook.data.DataConvert;
import com.oppo.MarkBook.data.NoteData;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;

/**
 * 添加笔记弹窗面板
 * @author steve
 * @since 2021-12-18 23:02
 */

public class AddNoteDialog extends DialogWrapper {
    /** 标题*/
    private EditorTextField tfTitle;
    /** 内容*/
    private EditorTextField tfMark;

    /**
     * 弹出对话框，输入标题
     */
    public AddNoteDialog() {
        super(true);
        init();
        setTitle("添加笔记");
    }

    /**
     * 弹出对话框，获取用户编辑的笔记内容
     *
     * @return JComponent
     */
    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        // 创建面板，默认位笔记标题和笔记内容
        JPanel panel = new JPanel(new BorderLayout());
        tfTitle = new EditorTextField("笔记标题");
        tfMark = new EditorTextField("笔记内容");
        // 设置弹框的宽高
        tfMark.setPreferredSize(new Dimension(200, 100));
        // 添加到面板种
        panel.add(tfTitle, BorderLayout.NORTH);
        panel.add(tfMark, BorderLayout.CENTER);
        return panel;
    }


    /**
     * 创建底部的按钮
     * @return JComponent
     */
    @Override
    protected JComponent createSouthPanel() {
        JPanel panel = new JPanel();
        // 创建按钮
        JButton button = new JButton("添加笔记到列表");
        // 按钮点击事件处理
        button.addActionListener(e -> {
            String title = tfTitle.getText();
            String mark = tfMark.getText();
            // 获取当前选中文本所在文件的类型
            String fileType = DataCenter.CURRENT_FILE_NAME.substring(DataCenter.CURRENT_FILE_NAME.lastIndexOf(".") + 1);
            // todo 写个美剧+function<T,R>.apply 函数
            if ("class".equals(fileType)) {
                fileType = "java";
            }
            if ("md".equals(fileType)) {
                fileType = "markdown";
            }
            if ("sh".equals(fileType)) {
                fileType = "shell";
            }
            // 创建笔记数据
            NoteData noteData = new NoteData(title, mark, DataCenter.SELECTED_TEXT, DataCenter.CURRENT_FILE_NAME, fileType);
            DataCenter.NOTE_LIST.add(noteData);
            //System.out.println(DataCenter.NOTE_LIST);
            DataCenter.TABLE_MODEL.addRow(DataConvert.convert(noteData));
            MessageDialogBuilder.yesNo("操作结果", "添加成功");
            // 关闭弹窗
            AddNoteDialog.this.dispose();
        });
        panel.add(button);
        return panel;
    }
}
